package com.glorystone.ins.service.impl;

import com.glorystone.ins.common.common.PageVo;
import com.glorystone.ins.dao.ChannelMapper;
import com.glorystone.ins.dao.CreditTotalMapper;
import com.glorystone.ins.dao.DepositRecordMapper;
import com.glorystone.ins.domain.CreditRecord;
import com.glorystone.ins.domain.CreditTotal;
import com.glorystone.ins.domain.DepositRecord;
import com.glorystone.ins.interceptor.PageList;
import com.glorystone.ins.service.CreditTotalService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;

/**
 * Created by wangwei on 2018/3/14.
 */
@Slf4j
@Service
public class CreditTotalServiceImpl implements CreditTotalService {

    @Autowired
    private CreditTotalMapper creditTotalMapper;
    @Autowired
    private ChannelMapper channelMapper;
    @Autowired
    private DepositRecordMapper depositRecordMapper;


    @Override
    public CreditTotal findCurrentByChannelId(Long channelId) {
        return creditTotalMapper.findCurrentByChannelId(channelId);
    }

    @Override
    public PageList<CreditTotal> findHistoryList(PageVo vo) {
        return creditTotalMapper.findHistoryList(vo, vo.getPageable());
    }

    @Override
    public void save(CreditTotal total) {
        creditTotalMapper.save(total);
    }

    @Override
    public boolean operateCreditQuota(Long channelId, CreditRecord.TypeEnum operate, BigDecimal amount, LocalDate date) {
        if (amount == null || BigDecimal.ZERO.compareTo(amount) == 0) {
            log.warn("操作渠道授信失败，金额不存在!  channelId-->{}, operate-->{}, amount-->{}", channelId, operate.name(), amount);
            return false;
        }

        switch (operate) {
            case DECREASE:
                // 减少额度
                CreditTotal current = creditTotalMapper.findCurrentByChannelId(channelId);
                if (current == null) {
                    log.warn("不存在生效中的渠道授信  channelId-->{}, operate-->{}, amount-->{}", channelId, operate.name(), amount);
                    return false;
                }
                current.setLastAmount(current.getLastAmount().subtract(amount));
                if (current.getAddUpAmount() == null) {
                    current.setAddUpAmount(amount);
                } else {
                    current.setAddUpAmount(current.getAddUpAmount().add(amount));
                }
                creditTotalMapper.update(current);


                break;
            case INCREASE:
                // 返还额度
                CreditTotal total = creditTotalMapper.findInTime(channelId, date);
                if (total == null) {
                    log.warn("不存在该渠道授信  channelId-->{}, operate-->{}, amount-->{}", channelId, operate.name(), amount);
                    return false;
                }

                total.setLastAmount(total.getLastAmount().add(amount));
                if (total.getAddUpReturnAmount() == null) {
                    total.setAddUpReturnAmount(amount);
                } else {
                    total.setAddUpReturnAmount(total.getAddUpReturnAmount().add(amount));
                }
                creditTotalMapper.update(total);


                break;
            default:
                break;
        }


        return true;
    }

    /**
     * 操作保证金
     * <p>
     *     注意：
     *     1. 当渠道有未补齐的保证金，不能进行授信申请操作
     * </p>
     * @param channelId 渠道id
     * @param operate 操作事项 // 1.缴纳保证金 PAY 2.补缴保证金SUPPLEMENT 3.逾期扣款OVERDUE 4.退保扣款RETURN 5.退回保证金RETURN_DEPOSIT 6.结算扣款SETTLEMENT
     * @param amount 操作金额
     * @return// 1.缴纳保证金 2.补缴保证金 3.逾期扣款 4.退保扣款， 5.退回保证金 6.结算扣款
     */
    @Override
    public boolean operateDeposit(Long channelId, DepositRecord.TypeEnum operate, BigDecimal amount, String remark) {
        if (amount == null || BigDecimal.ZERO.compareTo(amount) == 0) {
            log.warn("<--保证金操作失败， 操作金额不存在！ channelId-->{}, operate-->{}, amount-->{}", channelId, operate.name(), amount);
            return false;
        }



        switch (operate) {
            case PAY:
                CreditTotal total = creditTotalMapper.findOneInWorkFlow(channelId);
                if (total == null) {
                        log.warn("不存在审批中的渠道授信 channelId-->{}, operate-->{}, amount-->{}", channelId, operate.name(), amount);
                        return false;
                }
                total.setDepositLastAmount(total.getDepositLastAmount().add(amount));
                creditTotalMapper.update(total);

                DepositRecord record = DepositRecord.builder()
                        .channelId(channelId)
                        .lastAmount(total.getDepositLastAmount())
                        .creditId(total.getTid())
                        .operateAmount(amount)
                        .type(operate.getValue())
                        .content(operate.getContent())
                        .build();
                depositRecordMapper.save(record);

                break;
            case SUPPLEMENT:

                CreditTotal current = creditTotalMapper.findCurrentByChannelId(channelId);
                if (current == null) {
                    log.warn("不存在生效中的渠道授信  channelId-->{}, operate-->{}, amount-->{}", channelId, operate.name(), amount);
                    return false;
                }
                current.setDepositLastAmount(current.getDepositLastAmount().add(amount));
                creditTotalMapper.update(current);

                DepositRecord record2 = DepositRecord.builder()
                        .channelId(channelId)
                        .lastAmount(current.getDepositLastAmount()).creditId(current.getTid())
                        .operateAmount(amount)
                        .content(operate.getContent())
                        .type(operate.getValue()).build();
                depositRecordMapper.save(record2);

                break;
            case OVERDUE:

                CreditTotal current3 = creditTotalMapper.findCurrentByChannelId(channelId);
                if (current3 == null) {
                    log.warn("不存在生效中的渠道授信  channelId-->{}, operate-->{}, amount-->{}", channelId, operate.name(), amount);
                    return false;
                }
                current3.setDepositLastAmount(current3.getDepositLastAmount().subtract(amount));
                creditTotalMapper.update(current3);

                DepositRecord record3 = DepositRecord.builder()
                        .channelId(channelId)
                        .lastAmount(current3.getDepositLastAmount())
                        .creditId(current3.getTid())
                        .operateAmount(amount)
                        .content(operate.getContent())
                        .type(operate.getValue()).build();
                depositRecordMapper.save(record3);


                break;
            case RETURN:

                CreditTotal current4 = creditTotalMapper.findCurrentByChannelId(channelId);
                if (current4 == null) {
                    log.warn("不存在生效中的渠道授信  channelId-->{}, operate-->{}, amount-->{}", channelId, operate.name(), amount);
                    return false;
                }
                current4.setDepositLastAmount(current4.getDepositLastAmount().subtract(amount));
                creditTotalMapper.update(current4);

                DepositRecord record4 = DepositRecord.builder()
                        .channelId(channelId)
                        .lastAmount(current4.getDepositLastAmount()).creditId(current4.getTid())
                        .operateAmount(amount)
                        .content(operate.getContent())
                        .type(operate.getValue()).build();
                depositRecordMapper.save(record4);
                break;
            case RETURN_DEPOSIT:
                CreditTotal creditTotal = creditTotalMapper.findOneInWorkFlow(channelId);
                if (creditTotal == null) {
                    log.warn("不存在审批中的渠道授信 channelId-->{}, operate-->{}, amount-->{}", channelId, operate.name(), amount);
                    return false;
                }
                creditTotal.setDepositLastAmount(creditTotal.getDepositLastAmount().subtract(amount));
                creditTotalMapper.update(creditTotal);

                DepositRecord record5 = DepositRecord.builder()
                        .channelId(channelId)
                        .lastAmount(creditTotal.getDepositLastAmount())
                        .creditId(creditTotal.getTid())
                        .operateAmount(amount)
                        .type(operate.getValue())
                        .content(operate.getContent())
                        .build();
                depositRecordMapper.save(record5);
                break;
            case SETTLEMENT:
                CreditTotal current6 = creditTotalMapper.findCurrentByChannelId(channelId);
                if (current6 == null) {
                    log.warn("不存在生效中的渠道授信  channelId-->{}, operate-->{}, amount-->{}", channelId, operate.name(), amount);
                    return false;
                }
                current6.setDepositLastAmount(current6.getDepositLastAmount().subtract(amount));
                creditTotalMapper.update(current6);

                DepositRecord record6 = DepositRecord.builder()
                        .channelId(channelId)
                        .lastAmount(current6.getDepositLastAmount()).creditId(current6.getTid())
                        .operateAmount(amount)
                        .content(operate.getContent())
                        .type(operate.getValue()).build();
                depositRecordMapper.save(record6);
                break;
            default:
                break;
        }


        return true;
    }

    @Override
    public void updateOffByChannelIds(List<Long> channelIds) {
        creditTotalMapper.updateOffByChannelIds(channelIds);
    }

    @Override
    public List<CreditTotal> findActiveList() {
        return creditTotalMapper.findActiveList();
    }

    @Override
    public CreditTotal findPrePhase(Long channelId) {
        return creditTotalMapper.findPrePhase(channelId);
    }



}
